package de.argh.jteas.mojo.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
import org.apache.velocity.runtime.resource.util.StringResourceRepositoryImpl;

import sun.misc.IOUtils;
import de.argh.jteas.mojo.model.ASClass;
import de.argh.jteas.mojo.model.settings.Settings;

public class TemplateController {

	private Logger log;
	private Settings settings;
	private VelocityEngine engine;

	public TemplateController(Settings settings) {
		this.settings = settings;

		engine = new VelocityEngine();
		engine.setProperty("resource.loader", "classpath");
		engine.setProperty("classpath.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		engine.init();
	}

	public void generateSourceForClassesWith(List<ASClass> asClasses, String templateFile) throws Exception {

		for (ASClass clazz : asClasses) {

			VelocityContext context = new VelocityContext();
			context.put("class", clazz);
			context.put("settings", settings);

			Template template = engine.getTemplate("/resources/"+templateFile);

			String separator = String.valueOf(File.separatorChar);
			String fileName = clazz.getPackageName().replace(".", separator) + separator + clazz.getName() + ".as";

			String completeFileName = settings.getAsDirectory() + separator + fileName;
			getLog().info(completeFileName);
			File f = new File(completeFileName);
			if (!f.exists()) createPathToFile(completeFileName.substring(0, completeFileName.lastIndexOf(separator)));
			
			BufferedWriter writer =	new BufferedWriter(new FileWriter(f));

			template.merge(context, writer);

			writer.flush();
			writer.close();

			getLog().info("Class " + clazz.getName() + " generated!");
		}
	}

	private void createPathToFile(String fullQPath) {
		File f = new File(fullQPath);
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	public Logger getLog() {
		if (log == null) {

			synchronized (this) {
				if (log != null) { return log;

				}
				log = Logger.getLogger("standard");
			}
		}
		return log;
	}
}
